package com.banksoft.admin.thread;

import com.banksoft.admin.bean.MemberType;
import com.banksoft.admin.bean.OrderStatus;
import com.banksoft.admin.dao.OrderDao;
import com.banksoft.admin.dao.UserDao;
import com.banksoft.admin.entity.Order;
import com.banksoft.admin.entity.User;
import com.banksoft.admin.service.BaseService;
import com.banksoft.admin.service.OrderService;
import com.banksoft.admin.service.UserService;
import com.banksoft.util.StringUtil;
import org.apache.poi.hssf.record.UserSViewEnd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * 如果区域合伙人满一年后  后台没有续签 则自动取消
 */
@Component
public class UserTask implements InitializingBean {

    @Autowired
    UserService userService;
    @Autowired
    BaseService baseService;

    private static boolean isStart = false;
    private static Logger logger = LoggerFactory.getLogger(UserTask.class);
    private ExecutorService exec = Executors.newCachedThreadPool();

    @Override
    public void afterPropertiesSet() throws Exception {
        if(!isStart){
            logger.info("取消区域合伙人初始化任务执行....  " + new Date());
          //  exec.submit(new UserCancelTask());
         //   isStart = true;
        }
    }
    /**
     * 模板消息任务
     */
    class UserCancelTask implements Runnable{
        @Override
        public void run() {
            while(true){
                logger.info("开始执行定时取消区域合伙人任务******  " + new Date());
                //取出所有的区域合伙人  如果成为区域合伙人的时间满一年  则取消
                List<User> list = userService.listPartnerUser();
                if(StringUtil.isNotEmpty(list)) {
                    long now = System.currentTimeMillis();
                    for (User user : list) {
                        Long time = user.getPartnerDate();
                        if(time!=null){
                           // if((now-time)>(365*24*60*60*1000)){//超过24小时
                            if(((now-time)/(1000*60*60*24))>365){
                                user.setType(MemberType.Customer.name());
                                baseService.update(UserDao.class,user);
                            }
                        }else{//没有区域合伙人的时间  则取消
                            user.setType(MemberType.Customer.name());
                            baseService.update(UserDao.class,user);
                        }
                    }
                }
                try {
                    //每6个小时执行
                    Thread.sleep(6 * 60 * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }

}
